# micropython ESP32-CAM 摄像头拍照
# MicroPico plugins

from machine import Pin
import uos
from machine import SDCard
import camera
import utime
import time

# 声明引脚 4 作为LED的引脚
led_pin = Pin(4, Pin.OUT)

# enable station interface and connect to WiFi access point
import network, ntptime

# 启动WiFi
def start_WiFi():
    wlan = None
    try:
        wlan = network.WLAN(network.STA_IF)
        if wlan.isconnected():
            wlan.disconnect()
        wlan.active(True)
    except Exception as e:
        print(e)
    return wlan

# 断开WiFi
def stop_WIFI(wlan):
    try:
        if wlan.isconnected():
            wlan.disconnect()
        wlan.active(False)
    except Exception as e:
        print(e)

# 连接WiFi
def connect_WIFI(wlan, ip:str='', key:str=''):
    if str != '' and key != '':
        wlan.connect(ip, key)
        while not wlan.isconnected():
            utime.sleep(1)
        print('network config: ', wlan.ifconfig())
        # wlan.isconnected()
    
def scan_WIFI(wlan):
    try:
        networks = wlan.scan()   #list
        # 打印扫描结果
        for ssid, bssid, channel, rssi, authmode, hidden in networks:
            print("SSID: %s, Channel: %d, RSSI: %d" % (ssid.decode(), channel, rssi))
            if ssid.decode() == 'IOT':
                print("Connect to WiFi: ", ssid.decode())
                connect_WIFI(wlan, 'IOT', 'zhxlx54321')
                return True
            if ssid.decode() == 'xhz':
                print("Connect to WiFi: ", ssid.decode())
                connect_WIFI(wlan, 'xhz', '123456789)')
                return True
    except Exception as e:
        print(e)
    return None

def open_camera():
    #完整API
    state = False
    try:
        state = camera.init(0, format=camera.JPEG)
    except Exception as e:
        camera.deinit()
        state = camera.init(0, format=camera.JPEG)
    print("Camera State: ", state)

def capture_save():
    # 拍照之前点亮led灯
    try:
        led_pin.value(1)
        frame = camera.capture()
    except Exception as e:
        print(e)
    # 拍照之后关闭led灯
    led_pin.value(0)
    
    a=utime.localtime()
    filename = "img_{}{}{}{}{}{}.jpg".format(a[0],a[1],a[2],a[3],a[4],a[5])
    
    img=open(filename,"w")
    img.write(frame)
    img.close()
    
    print(filename)
    
def config_camera():
    # 其他设置：
    # 上翻下翻
    camera.flip(1)
    #左/右
    camera.mirror(1)

    # 分辨率camera.FRAME_HD
    camera.framesize(camera.FRAME_HD)
    # 选项如下：
    # FRAME_96X96 FRAME_QQVGA FRAME_QCIF FRAME_HQVGA FRAME_240X240
    # FRAME_QVGA FRAME_CIF FRAME_HVGA FRAME_VGA FRAME_SVGA
    # FRAME_XGA FRAME_HD FRAME_SXGA FRAME_UXGA FRAME_FHD
    # FRAME_P_HD FRAME_P_3MP FRAME_QXGA FRAME_QHD FRAME_WQXGA
    # FRAME_P_FHD FRAME_QSXGA
    # 有关详细信息，请查看此链接：https://bit.ly/2YOzizz

    # 特效
    camera.speffect(camera.EFFECT_NONE)
    #选项如下：
    # 效果\无（默认）效果\负效果\ BW效果\红色效果\绿色效果\蓝色效果\复古效果
    # EFFECT_NONE (default) EFFECT_NEG \EFFECT_BW\ EFFECT_RED\ EFFECT_GREEN\ EFFECT_BLUE\ EFFECT_RETRO

    # 白平衡
    #camera.whitebalance(camera.WB_OFFICE)
    #选项如下：
    # WB_NONE (default) WB_SUNNY WB_CLOUDY WB_OFFICE WB_HOME

    # 饱和
    camera.saturation(0)
    #-2,2（默认为0）. -2灰度
    # -2,2 (default 0). -2 grayscale 

    # 亮度
    camera.brightness(0)
    #-2,2（默认为0）. 2亮度
    # -2,2 (default 0). 2 brightness

    # 对比度
    camera.contrast(1)
    #-2,2（默认为0）.2高对比度
    #-2,2 (default 0). 2 highcontrast

    # 质量
    camera.quality(10)
    #10-63数字越小质量越高
    
    print("config camera")
    
def mount_sd():
    # 挂载sd卡到sd文件夹
    try:
        uos.mount(SDCard(), "/sd")
    except Exception as ret:
        print("挂载失败...", ret)
    else:
        print("挂载成功...")

    uos.chdir('sd') #切换到sd卡目录
    a = uos.listdir() #查看文件下所有的文件
    print(a)

def run():
    print("start esp32 cam")
    connectWiFi()
    open_camera()
    config_camera()
    mount_sd()
    
    while True:
        
        capture_save()
        
        # 计算下一分钟开始的时间戳
        #next_minute = utime.time() + 60 - (utime.time() % 60)
        next_minute = utime.time() + 10
        # 等待到下一分钟开始
        utime.sleep(next_minute - utime.time())
        
run()
